package com.awspaas.user.apps.sts.event;

import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListenerInterface;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.publicservice.util.HttpClientUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
*@Author:JF
*@Description:sts系统流程节点创建后调用sts接口，告知节点生成成功
*@Date:2023/6/20 15:33
*@parm:  * @param null
*/
public class ProcessAfterCreateNotify implements ExecuteListenerInterface {
    @Override
    public void execute(ProcessExecutionContext pec) throws Exception {
        String processInstId=pec.getProcessInstance().getId();
        String nodeName = SDK.getRepositoryAPI().getProcessExtendAttribute(pec.getProcessInstance().getProcessDefId(), "NODE_NAME");

       // String signkey ="SETRUST"; //签名key
        String signkey =SDK.getAppAPI().getProperty("com.awspaas.user.apps.public.service","SIGN_KEY"); //签名key
       // String host = "http://oatest.zjtrust.com:9184/admin-flow/api";  //域名
        String host=SDK.getAppAPI().getProperty("com.awspaas.user.apps.public.service","STS_DOMAIN");
        //String url = "/blade-apply/capitalApply/bpmProcessNotice";  //接口地址
        String url=SDK.getAppAPI().getProperty("com.awspaas.user.apps.public.service","STS_AFTER_TASK");
        Map<String,Object> params = new HashMap<>();
        params.put("nodeName",nodeName);
        params.put("processInstId",processInstId);
        Long timestamp = System.currentTimeMillis();
        String sign = sign(params,timestamp,signkey);
        params.put("sign",sign);
/*        String result = HttpUtil.createPost(host + url)
                .body(JSON.toJSONString(params)).timeout(15000)
                .header("timestamp", String.valueOf(timestamp)).execute().body();*/

        String result = HttpClientUtil.doPostJson(host + url, JSON.toJSONString(params), String.valueOf(timestamp));
        System.out.println("请求信托服务接口返回值：" + result);
        JSONObject obj = JSON.parseObject(result);
        System.out.println(obj);
    }

    @Override
    public String getVersion() {
        return "1.0";
    }

    @Override
    public String getDescription() {
        return "sts系统流程节点创建后调用sts接口，告知节点生成成功";
    }

    @Override
    public String getProvider() {
        return "aws";
    }

    /**
     * 获取签名
     * @param params 参数
     * @param timestamp 时间戳
     * @return String
     */
    public static String sign(Map<String, Object> params, Long timestamp, String signkey) {
        params.put("timestamp",timestamp);
        String toSignString = getFormatParams(params) + "&key=" + signkey;
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            byte[] b = toSignString.getBytes();
            byte[] digest = md5.digest(b);
            char[] chars = new char[] { '0', '1', '2', '3', '4', '5',
                    '6', '7' , '8', '9', 'A', 'B', 'C', 'D', 'E','F' };
            StringBuilder sb = new StringBuilder();
            for (byte bb : digest) {
                sb.append(chars[(bb >> 4) & 15]);
                sb.append(chars[bb & 15]);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }


    private static String getFormatParams(Map<String, Object> params){
        List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(params.entrySet());
        Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
            public int compare(Map.Entry<String, Object> arg0, Map.Entry<String, Object> arg1) {
                return (arg0.getKey()).compareTo(arg1.getKey());
            }
        });
        StringBuilder ret = new StringBuilder();
        for (Map.Entry<String, Object> entry : infoIds) {
            ret.append(entry.getKey());
            ret.append("=");
            ret.append(entry.getValue());
            ret.append("&");
        }
        ret = new StringBuilder(ret.substring(0, ret.length() - 1));
        return ret.toString();
    }




 }
